$(function() {
	var obj = {
		skuid: $(".id"), 					//商品id	
		name: $('.Name'), 					//姓名
		tel: $('.telephone'), 				//联系方式
		Province: $('.province'), 			//省
		City: $('.city'), 					//市
		Area: $('.area'), 					//区
		paymentTotal: $('.paymentTotal'), 	//支付窗口的总价值
		adressId: 0, 						//收货地址ID
		formHoutai: $('.formHoutai'),		//账户集分
		formCount: $('.formCount'),			//商品需要集分
		Goodid: null, 						//商品id	
		skuIdLong: null 					//skuid
	}
	// 取出商品列表界面传过来的参数  
	function GetRequest() {
		var url = location.search;
		var theRequest = new Object();
		if(url.indexOf("?") != -1) {
			var str = url.substr(1);
			strs = str.split("&");
			for(var i = 0; i < strs.length; i++) {
				theRequest[strs[i].split("=")[0]] = decodeURI(strs[i].split("=")[1]);
			}
		}
		return theRequest;
	}
	var title;
	var img;
	var price;
	var num;
	var orderNum;
	var total;
	var skuid;
	var shuxingzhi;
	var goodsType = 0;		// 商品类型
	if(localStorage.getItem('thisPoint')) {
		var Arr = JSON.parse(localStorage.getItem('thisPoint'));
		console.log(Arr);
		showGood(Arr);
		for(var i = 0;i < Arr.length;i++){
			Arr[i].goodType == '3' ? goodsType = 3 : goodsType = 2;
		}
		$('#num.boot_red').html(Arr[0].totalNum);
		$('.boot_red.price').html(Arr[0].totalPrice);
		$('.paymentTotal').text(Arr[0].totalPrice);
	} else {
		if(localStorage.getItem('data_title') && localStorage.getItem('point')) {
			localStorage.removeItem("data_zero");
			var adressData = JSON.parse(localStorage.getItem('data_title'));
			var pointH = localStorage.getItem('point');
			console.log(pointH);
			//console.log(adressData);
			for(var i = 0; i < adressData.length - 1; i++) {
				title = adressData[i].title;
				skuid = adressData[i].skuid;
				price = adressData[i].price;
				img = adressData[i].img;
				orderNum = adressData[i].num;
				shuxingzhi = adressData[i].shuxingzhi;
				point = adressData[i].point;
				showItem(img, title, price, orderNum, skuid, shuxingzhi, point);
			}
			$('.balance').text(adressData[adressData.length - 1]);
			$("#credits").text(pointH);
			//获取商品数量
			var number = $(".orderNum");
			var shop_num = 0;
			for(var j = 0; j < number.length; j++) {
				shop_num += (number[j].innerHTML - 0);
			}
			$("#num").text(shop_num);
		} else {
			localStorage.removeItem("data_title");
			var adressData = JSON.parse(localStorage.getItem('data_zero'));
			var pointH = localStorage.getItem('ragH');
			//console.log(adressData);
			for(var i = 0; i < adressData.length - 1; i++) {
				title = adressData[i].title;
				skuid = adressData[i].skuid;
				price = adressData[i].price;
				img = adressData[i].img;
				orderNum = adressData[i].num;
				shuxingzhi = adressData[i].shuxingzhi;
				point = adressData[i].point;
				showItem(img, title, price, orderNum, skuid, shuxingzhi, point);
			}
			$('.balance').text(adressData[adressData.length - 1]);
			$("#credits").text(pointH);
			//console.log($('.balance').text());
			//获取商品数量
			var number = $(".orderNum");
			var shop_num = 0;
			for(var j = 0; j < number.length; j++) {
				shop_num += (number[j].innerHTML - 0);
			}
			$("#num").text(shop_num);
		}
	}

	//动态创建标签
	function showItem(img, title, price, num, skuid, shuxingzhi) {
		var orderDetail_con = $('<div class="orderDetail_con"></div>');
		var id = $('<div class="id">' + skuid + '</div>');
		var div_order = $('<div class="orderDetail_con_lt"> <div class = "lt_imgBox" ><img src= ' + img + ' /></div></div>');
		var div_detail = $('<div class="orderDetail_con_rt"><div class="p_top"><p class="name"> ' + title + '</p><p class="red">￥<span class="price red">' + price + '</span>+<span class="point">' + point + '</span>集分</p></div><p class="p_bot"><span class="attr"> ' + shuxingzhi + '</span><span class="red">x<span class="orderNum">' + num + '</span></span></p></div>');
		var delivery = $('<div class="delivery"><span>配送方式</span><div><span>默认快递</span><span>&nbsp;免邮&nbsp;</span><span>&gt;</span></div></div>');
		orderDetail_con.append(id).append(div_order).append(div_detail);
		$(".orderDetail_box").append(orderDetail_con).append(delivery);
	}

	function showGood(array) {
		var orderDetail_box = $('.orderDetail_box');
		var orderDetail_con = $('<div class="orderDetail_con"></div>');
		for(var i = 0; i < array.length; i++) {
			var id = $('<div class="id">' + array[i].skuId + '</div>');
			var div_order = $('<div class="orderDetail_con_lt"> <div class = "lt_imgBox" ><img src= ' + array[i].goodSrc + ' /></div></div>');
			var div_detail = $('<div class="orderDetail_con_rt"><div class="p_top"><p class="name"> ' + array[i].goodName + '</p><p class="red"><span class="price red">' + array[i].goodPrice + '</span></p></div><p class="p_bot"><span class="attr"> ' + array[i].skuState + '</span><span class="red">x<span class="orderNum">' + array[i].goodNum.substring(1,array[i].goodNum.length) + '</span></span></p></div>');
		}
		var delivery = $('<div class="delivery"><span>配送方式</span><div><span>默认快递</span><span>&nbsp;免邮&nbsp;</span><span>&gt;</span></div></div>');
		orderDetail_con.append(id).append(div_order).append(div_detail);
		orderDetail_box.append(orderDetail_con).append(delivery);
	}

	loadPage(); //进入页面加载地址
	function loadPage() {
		if(localStorage.getItem('data')) { //如果有编辑地址也的缓存地址加载缓存地址，首次进入页面加载地址页的默认地址
			var adressData = JSON.parse(localStorage.getItem('data'));
			obj.name.text(adressData.name);
			obj.tel.text(adressData.tel);
			obj.Province.text(adressData.sheng);
			obj.City.text(adressData.shi);
			obj.Area.text(adressData.qu);
			obj.adressId = adressData.id;
			confirmPay(); 	// 如果地址存在才可以使用下单功能
		} else {
			promptlyLoad();	// 先加载地址在调用支付功能
			confirmPay(); 	// 如果地址存在才可以使用下单功能
		}
	}

	//加载地址信息
	function promptlyLoad() {
		$.ajax({
			type: "post",
			url: "http://a.91jfk.com/Product/Address/address_default",
			dataType: 'json',
			success: function(res) {
				console.log(res);
				if(res.code == '1') {
					var data = res.msg;
					obj.adressId = data.id;
					obj.name.text(data.name);
					obj.tel.text(data.tel);
					obj.Province.text(data.area);
					obj.City.text(data.street);
					obj.Area.text(data.address);
				} else {
					$(".errAlert").text('请添加地址').addClass("AlertShow");
					setTimeout(function() {
						$(".errAlert").removeClass("AlertShow");
					}, 3000);
				}
			},
			error: function(err) {
				console.log(err)
			}
		});
	}

	//点击顶部跳转管理地址页面
	$('.cfmOrder_content').undelegate().delegate('.address', 'click', function() {
		window.location.href = 'guanlidizhi_exchange.html';
	});

	//点击确认下单按钮
	function confirmPay() {
		$('.cfmOrder_cfm').bind('click', function() {
			var idArr = [];
			var numArr = [];
			for(var i = 0; i < $(".id").length; i++) {
				idArr.push($(".id")[i].innerText);
			}
			var id = idArr.join(",");
			console.log(id);
			for(var i = 0; i < $(".orderNum").length; i++) {
				numArr.push($(".orderNum")[i].innerText - 0);
			}
			var num = (numArr.join(","));
			$('.cfmOrder_foot').css('display', 'none');
			$('.payment_foot').css('display', 'block');
			$('.mask').css('display', 'block');
			var FinalTotal = (($('.orderNum').text() - 0) * ($('.price').text() - 0)).toFixed(2);
			$(".paymentTotal").text($(".balance").text());
			var adressId = obj.adressId;
			console.log(id, num, adressId);
			$.ajax({
				type: "post",
				url: "http://a.91jfk.com/Product/Pointorder/duihuan_create_order",
				data: {
					skuid: id,
					address_id: adressId,
					goods_num: num
				},
				success: function(res) {
					var data = JSON.parse(res);
					console.log(data);
					if(data.code == 1) {
						console.log(goodsType);
						if (goodsType == 0) {
							obj.formHoutai.text(data.point_num);
							obj.formCount.text(data.point);
							if($(".balance").text() == "0.00") {
								if((data.point_num - 0) >= (data.point - 0)) {
									$('.mask').css('display','block');
									$('.cfmOrder_foot').css('display','none');
									$('.payment_foot').css('display','none');
									$('.pointPay').show().find('.point_sure').click("click",function(){
										$.ajax({
											url: "http://a.91jfk.com/Product/Nowbuy/des_num",
											type: "post",
											data: {
												orderid: data.orderid
											},
											dataType: 'json',
											success: function(res) {
												console.log(res);
												$(".errAlert").text(res.message).addClass("AlertShow");
												setTimeout(function() {
													$(".errAlert").removeClass("AlertShow");
												}, 3000);
												$('.mask').hide();
												$('.pointPay').hide();
												$('.cfmOrder_foot').css('display','block');
											},
											error: function(err) {
												console.log(err);
											}
										});
									}); 
								}else {
									$(".errAlert").text("您的积分余额不足...").addClass("AlertShow");
									setTimeout(function() {
										$(".errAlert").removeClass("AlertShow");
									}, 3000);
								}
							} else {
								//点击圆圈选择支付方式
								var payWay; //用于记录支付方式
								$('.mode_row').bind('click', function() {
									console.log(123);
									$(this).children('.row_Rt').find('.pur').addClass('addCir');
									$(this).siblings().children('.row_Rt').find('.pur').removeClass('addCir');
									var a = $(this).children('input[type=hidden]').val();
									payWay = $(this).children('.row_con').find('.mode_name').text();
									console.log(payWay);
								});
								var orderId = data.orderid;
								console.log(orderId);
								//点击确认支付
								$('.confirm_cfm').bind('click', function() {
									if(payWay == '微信支付') {
										console.log('微信支付')
										$.ajax({
											url: "http://a.91jfk.com/Product/WxJsAPI/jsApiCall",
											type: "post",
											data: {
												orderId: orderId
											},
											datatype: "json",
											success: function(xhr) {
												console.log(xhr);
												var data = JSON.parse(xhr);
												callpay(data.jsApiParameters);
											},
											error: function(mes) {
												console.log('支付失败');
											}
										}); //ajax结束
									} else if(payWay == '连连支付') {
										console.log('连连支付')
										//location.href = "../Lianlianpay/send/no_order/" + order; //连连接口
									} else {
										console.log('请选择付款方式...');
										$(".errAlert").text("请选择付款方式...").addClass("AlertShow");
										setTimeout(function() {
											$(".errAlert").removeClass("AlertShow");
										}, 3000);
									}
								});
							}
						} else {
							if(goodsType == 3) {
								obj.formHoutai.text(data.point_num);
								obj.formCount.text(data.point);
								if((data.point_num - 0) >= (data.point - 0)) {
									$('.mask').css('display','block');
									$('.cfmOrder_foot').css('display','none');
									$('.payment_foot').css('display','none');
									$('.pointPay').show().find('.point_sure').click("click",function(){
										$.ajax({
											url: "http://a.91jfk.com/Product/Nowbuy/des_num",
											type: "post",
											data: {
												orderid: data.orderid
											},
											dataType: 'json',
											success: function(res) {
												console.log(res);
												$(".errAlert").text(res.message).addClass("AlertShow");
												setTimeout(function() {
													$(".errAlert").removeClass("AlertShow");
												}, 3000);
												$('.mask').hide();
												$('.pointPay').hide();
												$('.cfmOrder_foot').css('display','block');
											},
											error: function(err) {
												console.log(err);
											}
										});
									}) 
								}else {
									$(".errAlert").text("您的积分余额不足...").addClass("AlertShow");
									setTimeout(function() {
										$(".errAlert").removeClass("AlertShow");
									}, 3000);
								}
							} else {
								//点击圆圈选择支付方式
								var payWay; //用于记录支付方式
								$('.mode_row').bind('click', function() {
									console.log(123);
									$(this).children('.row_Rt').find('.pur').addClass('addCir');
									$(this).siblings().children('.row_Rt').find('.pur').removeClass('addCir');
									var a = $(this).children('input[type=hidden]').val();
									payWay = $(this).children('.row_con').find('.mode_name').text();
									console.log(payWay);
								});
								var orderId = data.orderid;
								console.log(orderId);
								//点击确认支付
								$('.confirm_cfm').bind('click', function() {
									if(payWay == '微信支付') {
										console.log('微信支付')
										$.ajax({
											url: "http://a.91jfk.com/Product/WxJsAPI/jsApiCall",
											type: "post",
											data: {
												orderId: orderId
											},
											datatype: "json",
											success: function(xhr) {
												console.log(xhr);
												var data = JSON.parse(xhr);
												callpay(data.jsApiParameters);
											},
											error: function(mes) {
												console.log('支付失败');
											}
										}); //ajax结束
									} else if(payWay == '连连支付') {
										console.log('连连支付')
										//location.href = "../Lianlianpay/send/no_order/" + order; //连连接口
									} else {
										console.log('请选择付款方式...');
										$(".errAlert").text("请选择付款方式...").addClass("AlertShow");
										setTimeout(function() {
											$(".errAlert").removeClass("AlertShow");
										}, 3000);
									}
								});
							}
						}
					}else{
						$(".errAlert").text(res.msg).addClass("AlertShow");
						setTimeout(function() {
							$(".errAlert").removeClass("AlertShow");
						}, 3000);
					}
				},
				error: function(err) {
					console.log(err);
				}
			}); //AJAX结束
		});
	}

	//点击关闭按钮，关闭支付弹框
	$('.close').bind('click', function() {
		$('.cfmOrder_foot').css('display', 'block');
		$('.payment_foot').css('display', 'none');
		$('.mask').css('display', 'none');
	});

	//纯集分支付、取消支付
    $('.point_cancel').click(function(){
    	$('.mask').hide();
		$('.cfmOrder_foot').show();
		$('.pointPay').hide();
    });

	function callpay(arg) {
		if(typeof WeixinJSBridge == "undefined") {
			if(document.addEventListener) {
				document.addEventListener('WeixinJSBridgeReady', jsApiCall, false);
			} else if(document.attachEvent) {
				document.attachEvent('WeixinJSBridgeReady', jsApiCall);
				document.attachEvent('onWeixinJSBridgeReady', jsApiCall);
			}
		} else {
			jsApiCall(arg);
		}
	}

	//调用微信JS api 支付
	function jsApiCall(arg) {
		var data = JSON.parse(arg);
		WeixinJSBridge.invoke(
			'getBrandWCPayRequest',
			data,
			function(res) {
				WeixinJSBridge.log(res.err_msg);
				if(res.err_msg == "get_brand_wcpay_request:ok") {
					//alert("支付成功");
				} else if(res.err_msg == "get_brand_wcpay_request:cancel") {
					//alert("取消支付");
				} else {
					//alert(res.err_msg);
					//alert("支付失败");
				}
			});
	}
	//	window.onunload = function(){
	//		localStorage.clear();
	//	}
});